package com.redpack.redpost.struts.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.redpack.redpost.struts.form.admin.generalForm;

public class verArchivo1 extends Action {
	
	public ActionForward execute(
			ActionMapping mapping, 
			ActionForm form, 
			HttpServletRequest request, 
			HttpServletResponse response) throws Exception {
		
		generalForm f = ( generalForm ) form ;
		
		try{
			
			String fileName = f.getTexto( ),
					dirPath = getServlet().getServletContext().getRealPath("/");
			System.out.println("::::::::::::::::::::: " + dirPath ) ;
	        File file = new File ( "" +  dirPath + "/" + fileName ) ;
	        System.out.println("Absoluto :::::: " + file.getAbsolutePath() ) ;
	         
	        String usuario = "test1" ,
	                pass = "test1",
	                server = "127.0.0.1",	                
	                remotePath = "/" + fileName ;
	        
	     URL url = new URL("ftp://" + usuario + ":" + pass + "@" + server + remotePath + ";type=i");
       	 URLConnection urlc = url.openConnection( ) ;
       	 
       	InputStream input = urlc.getInputStream();
	   	 FileOutputStream out = new FileOutputStream( file ) ;
	   	 byte[] bos = new byte[500000];
	   	 int c;
	   	 while ((c = input.read(bos)) != -1) {
	   	 out.write(bos,0,c);        	 
	   	 }
	   	 
	   	 input.close( ) ;
	   	 out.close( ) ;
	   	 
	   	 FileInputStream fis = new FileInputStream ( file ) ; 
	   	 byte[ ] ArrayBytesRead = new byte[ fis.available() ] ;
	//   	 int read = 0 ;
	   	 fis.read( ArrayBytesRead ) ;
	   	 fis.close( ) ;
	   	        	 
	   	 response.setHeader("Expires", "0");
	        response.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
	   	 response.setHeader("Pragma", "public");
	   	 response.setHeader( "content-disposition" , "attachment; filename=ArchivoEnvio.pdf" ) ;
	   	 response.setContentType("application/pdf");
   	 
	   	 response.getOutputStream( ).write( ArrayBytesRead ) ;
		 response.getOutputStream( ).close( ) ;	
			
		}catch( Exception e ){
			e.printStackTrace( ) ;
		}
		
		return null ;
		
	}

}
